#include "UartDMARcv_Proc.h"

static inline void HAL_UART_IDLEProc(UART_HandleTypeDef *huart_src, UartProcInfo *uart_procinfo)
{
	uint32_t clearStatus = 0;
	uint8_t aRX_Count;
	
	if(__HAL_UART_GET_FLAG(huart_src, UART_FLAG_IDLE) != RESET)
	{
		if(huart_src == uart_procinfo->huart_dst)
		{
			__HAL_UART_CLEAR_IDLEFLAG(huart_src);
			HAL_UART_DMAStop(huart_src);
			clearStatus = huart_src->Instance->SR;
			clearStatus = huart_src->Instance->DR;
			clearStatus = clearStatus;
			
			aRX_Count = uart_procinfo->cu32RecvBufSize - __HAL_DMA_GET_COUNTER(huart_src->hdmarx);
			
			osMessagePut(uart_procinfo->RcvDoneMsgQueueHandle, aRX_Count, 1);
			uart_procinfo->u32RecvCnt = 0;
		}
	}
}

uint8_t InitUartProcInfo(UartProcInfo *uart_procinfo, UART_HandleTypeDef *huart, uint32_t u32RcvBufSz, uint8_t *p8RcvBuf, osMessageQId RcvDoneMsg)
{
	if(uart_procinfo == NULL || 
			(uart_procinfo->cu32RecvBufSize == 0 && u32RcvBufSz == 0)|| p8RcvBuf == NULL)
		return 0;
	
	uart_procinfo->huart_dst = huart;
	uart_procinfo->RcvDoneMsgQueueHandle = RcvDoneMsg;
	uart_procinfo->u32RecvCnt = 0;
	uart_procinfo->pu8RecvBuf = p8RcvBuf;
	
	return 1;
}

inline void UartDMAISR(UART_HandleTypeDef *huart_src, UartProcInfo *uart_procinfo)
{

  /* USER CODE BEGIN USART2_IRQn 0 */
  /* USER CODE END USART2_IRQn 0 */
	HAL_UART_IRQHandler(huart_src);
	HAL_UART_IDLEProc(huart_src, uart_procinfo);
  /* USER CODE BEGIN USART2_IRQn 1 */
	HAL_UART_Receive_DMA(huart_src, uart_procinfo->pu8RecvBuf, uart_procinfo->cu32RecvBufSize);

  /* USER CODE END USART2_IRQn 1 */
}
